import 'package:flutter/material.dart';
import "package:dio/dio.dart";
import 'dart:convert';

class SelfDioRequest extends StatefulWidget {
  @override
  _SelfDioRequestState createState() => _SelfDioRequestState();
}

class _SelfDioRequestState extends State<SelfDioRequest> {
  List _list = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("http库请求数据"),
      ),
      // 浮动按钮，方便添加事件
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          dio2();
        },
      ),
      body: ListView.builder(
        // 把数据渲染到页面上
        itemCount: _list.length,
        itemBuilder: (BuildContext context, int i) {
          return Text('${_list[i]["nm"]}');
        },
      ),
    );
  }

  dio1() async {
    //  new 一个Dio实例， 如果没有写new，直接写Dio() 也是可以的，作用一样，系统默认生成实例
    Dio dio = new Dio();
    // 得到请求回来的数据
    Response response =
        await dio.get('http://m.maoyan.com/ajax/movieOnInfoList?token=');

    // 对数据进行解析，把字符串转义为对象
    // Map 类似与String、List 都是
    Map<String, dynamic> responseData = json.decode(response.toString());

    print(responseData['movieList']);
    setState(() {
      _list = responseData['movieList'];
    });
  }

  dio2() {
    // 使用 .then 改写
    Dio dio = new Dio();
    dio
        .get('http://m.maoyan.com/ajax/movieOnInfoList?token=')
        .then((Response response) {
      Map<String, dynamic> responseData = json.decode(response.toString());

      print(responseData['movieList']);
      setState(() {
        _list = responseData['movieList'];
      });
    });
  }
}




/*

  // Map 类似于 String、List 都是数据类型，这个是键值对/对象
  // 尖括号里面的代表每一项的数据类型
  {"name": "司宇昭"}  <String, String>
  {"age": 20}  <String, int>
  // dynamic值泛型， 不规定数据类型

  Map<String, dynamic> responseData = json.decode(response.toString());

*/